import React, { PureComponent } from 'react'
import {
  message, Button, Alert, Popconfirm,
} from 'antd'
import { connect } from '@umijs/max'
import list2tree from 'list2tree'
import {
 ProTable, ProTableOperate, ProTableOptions, InputSearch,
} from '@/components'
import RoleModal from './roleModal'
import styles from './index.less'
import { getRoleById, delRole, getMenuList } from './api'

const { OperateItem } = ProTableOperate
const getNavTreeDataFunc = list2tree({
  idKey: 'id',
  parentIdKey: 'parentId',
  newKey: {
    key: 'id',
    name: 'menuName',
  },
})

@connect(({ global }) => ({ ...global }))
class Role extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      show: false,
      menuList: [],
    }
    this.modalRef = React.createRef()
  }

  componentDidMount() {
    this.getMenuList()
  }

  // 根据角色的menuList
  handleMenuList(record) {
    if (record && record.isSystem) {
      const handleFun = (arr) => arr.map((item) => {
        const obj = {
          name: item.name,
          key: item.id,
          check: true,
          edit: true,
        }
        if (item.children) obj.children = handleFun(item.children)
        return obj
      })
      return handleFun(this.state.menuList)
    }
    let checkList = []
    if (record && record.menuList) checkList = record.menuList
    const checkFun = (arr) => arr.map((item) => {
      const newItme = {
        name: item.name,
        key: item.id,
      }
      const obj = checkList.find((checkItem) => item.id === checkItem.menuId)
      if (obj) {
        if (obj.readWriteStatus === 1) {
          newItme.edit = true
          newItme.check = true
        } else if (obj.readWriteStatus === 0) {
          newItme.check = true
        }
      }
      if (item.children) newItme.children = checkFun(item.children)
      return newItme
    })
    return checkFun(this.state.menuList)
  }

  getMenuList = () => {
    getMenuList({ userId: this.props.user.id }).then(
      (res) => {
        this.setState({ menuList: getNavTreeDataFunc(res) })
      },
      (error) => {
        console.log(error)
      },
    )
  }

  fetchData = async () => {
    const { roleName } = this.state
    const tempQuery = {}
    if (roleName && roleName !== '') tempQuery.roleName = roleName
    this.setState({
      query: tempQuery,
    })
  }

  deleteRole = (id) => {
    delRole({ roleId: id }).then(
      (res) => {
        message.success('删除成功')
        this.fetchData()
      },
      (error) => {
      },
    )
  }

  onCheckClick = (record) => {
    getRoleById({ roleId: record.id }).then(
      (res) => {
        if (this.modalRef.current) this.modalRef.current.onCheckOpen(res, this.handleMenuList(res))
      },
      (error) => {
        console.log(error)
      },
    )
  }

  onEditClick = (record) => {
    getRoleById({ roleId: record.id }).then(
      (res) => {
        if (this.modalRef.current) this.modalRef.current.onEditOpen(res, this.handleMenuList(res))
      },
      (error) => {
        console.log(error)
      },
    )
  }

  onCloseCallBack = () => {
    this.fetchData()
  }

  render() {
    const { show } = this.state
    return (
      <div className={styles.secret_key_page}>
        <div className={styles.secret_key_title}>空间角色</div>
        <ProTableOperate
          toggleOperate={false} // 是否隐藏 收起/展开 按钮 (如果隐藏按钮，handleToggleSta设置属性值不生效)
          unfolded
        >
          <OperateItem align="left">
            <InputSearch
              placeholder="请输入角色名称"
              value={this.state.dsName}
              onChange={(e) => {}}
              onSearch={() => {}}
            />
          </OperateItem>
          <OperateItem itemType="btn">
            {
                [
                  <Button
                    type="primary"
                    onClick={() => this.modalRef.current.onNewOpen(this.handleMenuList([]))}
                    key="new"
                  >
                    添加角色
                  </Button>,
                ]
              }
          </OperateItem>
        </ProTableOperate>
        <ProTable
          url="/api/v1/authority/role/list"
          query={this.state.query}
          columns={[
            {
              title: '角色名称',
              dataIndex: 'roleName',
              width: '10%',
              key: 'roleName',
            },
            {
              title: '角色描述',
              dataIndex: 'roleDesc',
              width: '10%',
              key: 'roleDesc',
            },
            {
              title: '最近修改时间',
              dataIndex: 'updateTime',
              width: '10%',
              key: 'updateTime',
            },
            {
              title: '最近修改人',
              dataIndex: 'updateName',
              width: '10%',
              key: 'updateName',
            },
            {
              title: '操作',
              dataIndex: 'operation',
              width: '15%',
              key: 'operation',
              render: (text, record) => (
                <ProTableOptions>
                  <span
                    key="check"
                    onClick={() => {
                      this.onCheckClick(record)
                    }}
                  >
                    查看
                  </span>
                  {
                    !record.isSystem ? (
                      <span
                        key="edit"
                        onClick={() => {
                          this.onEditClick(record)
                        }}
                      >
                        编辑
                      </span>
                    ) : null
                  }
                  {
                    !record.isSystem ? (
                      <Popconfirm
                        title="确定要删除吗？"
                        onConfirm={() => { this.deleteRole(record.id) }}
                        visible={this.state.visibleDele === record.id}
                        onCancel={() => { this.setState({ visibleDele: false }) }}
                        okText="是"
                        cancelText="否"
                        key="del"
                      >
                        <span onClick={() => { this.setState({ visibleDele: record.id }) }}>
                          删除
                        </span>
                      </Popconfirm>
                    ) : null
                  }
                </ProTableOptions>
              ),
            },
          ]}
        />
        <RoleModal
          ref={this.modalRef}
          closeCallBack={this.onCloseCallBack}
        />
      </div>
    )
  }
}

export default Role
